$NG.AllReady(function (page, { useValuesChange, useClick, useDataIndexChange, useBeforeClick, useUpdateRows, useUpdateRow }) {
    // console.log("page is ready");
    console.log($NG.getPageUI());
    console.log($NG.getPageState());
    const mstform = $NG.getCmpApi("p_form_equipment_chg");
    const dgrid1 = $NG.getCmpApi("p_form_equipment_chg_d");
    const dgrid2 = $NG.getCmpApi("p_form_equipment_chg_impl");
    const dgrid3 = $NG.getCmpApi("p_form_equipment_chg_svc");
    const dgrid4 = $NG.getCmpApi("p_form_equipment_chg_rd");
    let dgrid5 = $NG.getCmpApi("p_form_equipment_chg_qz");

    const toolbarTop = $NG.getCmpApi("toolbar_top");
    const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_equipment_chg_d");
    const d1tool = $NG.getCmpApi("toolbar_p_form_equipment_chg_d");
    const d2tool = $NG.getCmpApi("toolbar_p_form_equipment_chg_impl");
    const d3tool = $NG.getCmpApi("toolbar_p_form_equipment_chg_svc");
    const d4tool = $NG.getCmpApi("toolbar_p_form_equipment_chg_rd");



    let project_total_amt = 0;
    let nfb_amt_vat = 0;
    let ncg_amt_vat = 0;
    let nzz_amt_vat = 0;
    let nfb_amt = 0;
    let ncg_amt = 0;
    let nzz_amt = 0;
    let cnt_amt = 0;
    let cnt_amt_vat = 0;
    let ss_amt = 0;
    let cg_amt = 0;
    let zz_amt = 0;
    let zz_amt_ori = 0;
    let nfb_b = 0;
    let ncg_b = 0;
    let nzz_b = 0;
    let ss_b = 0;
    let cg_b = 0;
    let zz_b = 0;
    let onLock = true;
    let timeId = 0;

    async function isWlag() {
        let lock = true
        let phid_pc = mstform.getItem("phid_pc").getValue()
        if (page.isList) {
            phid_pc = $NG.getCmpApi('grid').getSelectedRow().phid_pc
        }
        await $NG.execServer("getSbqdchgIsFlag", { phid_pc }, (res) => {
            if (res.count == 0) {
                return
            } else {
                const phid = JSON.parse(res.data)[0].extendObjects.phid
                const mphid = mstform.getValues().phid
                if(!mphid){
                    lock = false
                } else if(phid == mphid) {
                    lock = true
                } else {
                    lock = false
                }
            }
        })
        return lock
    }
    //隐藏表头表体单据引用按钮
    const toolbars = [
        { toolbar: toolbarTop, items: ["imp"] },
        { toolbar: d1tool, items: ["attachment", "addrow"] },
        { toolbar: d3tool, items: ["attachment", "imp", "addrow", "deleterow"] },
        { toolbar: d4tool, items: ["attachment", "imp", "addrow", "deleterow"] },
        { toolbar: d2tool, items: ["attachment", "imp", "addrow", "deleterow"] },
    ];
    toolbars.forEach(({ toolbar, items }) => {
        if (toolbar && typeof toolbar.getItem === "function") {
            items.forEach((item) => {
                const button = toolbar.getItem(item);
                if (button) {
                    button.setHidden(); // 隐藏按钮
                }
            });
        }
    });

    if (toolbar_dgrid) {
        console.log("toolbar_dgrid", toolbar_dgrid);
        toolbar_dgrid.getItem("imp").setProps({ children: "引用设备清单明细" });

        // 增加匹配物料
        toolbar_dgrid.insert({
            id: "user_match",
            text: "匹配物料",
            iconCls: "icon-InsertRow",
        });
        useClick(() => {
            window._list = [];
            window.sNum = 0;
            window.eNum = 0;
            $NG.message(`正在匹配物料，请等待完成，请勿操作！`);
            timeId = setInterval(() => {
                $NG.message(`正在匹配物料，总进度 ${(window.sNum / (dgrid1.getRows().length * 3 * 6)).toFixed(4) * 100}%`);
                if (window.sNum == window.eNum) {
                    //发起请求
                    $NG.message(`正在保存未有物料。总进度 50%！`);
                    // console.log(`数据准备就绪`, window._list);
                    clearInterval(timeId);
                    getWlRequest(window._list);
                } else {
                    window.eNum = window.sNum;
                }
            }, 1500);
            matchingWl();
        }, "user_match");
        toolbar_dgrid.insert({
            id: "add_item",
            text: "增行",
            iconCls: "icon-InsertRow",
        });
        useClick(() => {
            gzCntItem()
        }, "add_item")
        // hideData
        d1tool.insert({
            id: "hideData",
            text: "隐藏原有数据",
            iconCls: "icon-New",
        });

        d1tool.insert({
            id: "showData",
            text: "显示原有数据",
            iconCls: "icon-New",
        });

        useClick(() => {
            console.log("hideData");
            hiddenOriKey(true);
        }, "hideData");

        useClick(() => {
            console.log("showData");
            hiddenOriKey(false);
        }, "showData");
    }


    function gzCntItem() {
        $NG.external.openNGHelp({
            type: "NGSingleHelp",
            helpId: "pcm3_cnt_d_IdToName",
            valueField: "phid",
            labelField: "item_name",

        }).then(async (data) => {
            console.log(data)
            const temp = data.origin
            // const bool = await $NG.confirm('警告：点击确定后将会覆盖掉所有选中行的合同清单部分，是否继续？')
            // if(bool){
            // const rows = dgrid1.getSelectedData()
            // rows.forEach(item=>{
            // item.u_cnt_item_no = temp.ItemNo
            // item.u_cnt_item_name = temp.ItemName
            // item.u_cnt_item = temp.PhId
            // item.u_cnt_item_EXName = temp.ItemName
            // })
            dgrid1.addRows({
                u_cnt_item_no: temp.ItemNo,
                u_cnt_item_name: temp.ItemName,
                u_cnt_item: temp.PhId,
                u_cnt_item_EXName: temp.ItemName
            })
            // $NG.message("挂载成功！")
            // }

            //data:拿到帮助选中的数据
        })
    }
    //保存
    useBeforeClick(async () => {
        let isw = await isWlag()
        if (!isw) {
            $NG.alert("当前项目由设备清单在流程中，请勿重复发起，或等待上个流程结束！")
            return false
        }
        if (!staticData(dgrid1.getRows())) {
            return false
        }
        let errorItemData = [];
        // errorItemData = dgrid1.getData().reduce((value, item, index) => {
        //   if (item.u_sub_name && item.u_sub_name.trim() && (!item.u_sub_name?.trim() || !String(item.u_sub_item_category || "").trim() || !String(item.u_sub_item_msunit || "").trim() || !item.u_sub_spec?.trim())) {
        //     value.push(index + 1);
        //   }
        //   return value;
        // }, errorItemData);
        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if ((item.u_sub_name && item.u_sub_name.trim()) ||
                (item.u_sub_item_category && String(item.u_sub_item_category).trim()) ||
                (item.u_sub_item_msunit && String(item.u_sub_item_msunit).trim()) ||
                (item.u_sub_spec && item.u_sub_spec.trim())
            ) {
                if (
                    (item.u_sub_name && item.u_sub_name.trim()) &&
                    (item.u_sub_item_category && String(item.u_sub_item_category).trim()) &&
                    (item.u_sub_item_msunit && String(item.u_sub_item_msunit).trim()) &&
                    (item.u_sub_spec && item.u_sub_spec.trim())
                ) {
                    if (!item.u_sub_item) {
                        value.push(index + 1)
                    }
                } else {
                    value.push(index + 1)
                }
            }
            return value
        }, errorItemData)

        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if ((item.u_pur_name && item.u_pur_name.trim()) ||
                (item.u_pur_item_category && String(item.u_pur_item_category).trim()) ||
                (item.u_pur_item_msunit && String(item.u_pur_item_msunit).trim()) ||
                (item.u_pur_spec && item.u_pur_spec.trim())
            ) {
                if (
                    (item.u_pur_name && item.u_pur_name.trim()) &&
                    (item.u_pur_item_category && String(item.u_pur_item_category).trim()) &&
                    (item.u_pur_item_msunit && String(item.u_pur_item_msunit).trim()) &&
                    (item.u_pur_spec && item.u_pur_spec.trim())
                ) {
                    if (!item.u_pur_item) {
                        value.push(index + 1)
                    }
                } else {
                    value.push(index + 1)
                }
            }
            return value
        }, errorItemData)

        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if ((item.u_self_name && item.u_self_name.trim()) ||
                (item.u_self_item_category && item.u_self_item_category.trim()) ||
                (item.u_self_item_msunit && item.u_self_item_msunit.trim()) ||
                (item.u_self_spec && item.u_self_spec.trim())
            ) {
                if (
                    (item.u_self_name && item.u_self_name.trim()) &&
                    (item.u_self_item_category && item.u_self_item_category.trim()) &&
                    (item.u_self_item_msunit && item.u_self_item_msunit.trim()) &&
                    (item.u_self_spec && item.u_self_spec.trim())
                ) {
                    if (!item.u_self_item) {
                        value.push(index + 1)
                    }
                } else {
                    value.push(index + 1)
                }
            }
            return value
        }, errorItemData)


        // errorItemData = dgrid1.getData().reduce((value, item, index) => {
        //   if (item.u_pur_name && item.u_pur_name.trim() && (!item.u_pur_name?.trim() || !String(item.u_pur_item_category || "").trim() || !String(item.u_pur_item_msunit || "").trim() || !item.u_pur_spec?.trim())) {
        //     value.push(index + 1);
        //   }
        //   return value;
        // }, errorItemData);
        // errorItemData = dgrid1.getData().reduce((value, item, index) => {
        //   if (item.u_self_name && item.u_self_name.trim() && (!item.u_self_name?.trim() || !String(item.u_self_item_category || "").trim() || !String(item.u_self_item_msunit || "").trim() || !item.u_self_spec?.trim())) {
        //     value.push(index + 1);
        //   }
        //   return value;
        // }, errorItemData);
        errorItemData = Array.from(new Set(errorItemData)).sort((a, b) => a - b);
        if (errorItemData.length !== 0) {
            $NG.alert(`第 ${errorItemData.join("、")} 行，数据不符合规范。请查看规格、单位、分类是否有字段为空 或者 未匹配物料！`);
            return false;
        } else {
            return true;
        }
    }, "save");

    useBeforeClick(async () => {
        let isw = await isWlag()
        if (!isw) {
            $NG.alert("当前项目由设备清单在流程中，请勿重复发起，或等待上个流程结束！")
            return false
        }
        let errorItemData = [];
        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if (item.u_sub_name.trim() && (!item.u_sub_name?.trim() || !String(item.u_sub_item_category || "").trim() || !String(item.u_sub_item_msunit || "").trim() || !item.u_sub_spec?.trim())) {
                value.push(index + 1);
            }
            return value;
        }, errorItemData);
        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if (item.u_pur_name.trim() && (!item.u_pur_name?.trim() || !String(item.u_pur_item_category || "").trim() || !String(item.u_pur_item_msunit || "").trim() || !item.u_pur_spec?.trim())) {
                value.push(index + 1);
            }
            return value;
        }, errorItemData);
        errorItemData = dgrid1.getData().reduce((value, item, index) => {
            if (item.u_self_name.trim() && (!item.u_self_name?.trim() || !String(item.u_self_item_category || "").trim() || !String(item.u_self_item_msunit || "").trim() || !item.u_self_spec?.trim())) {
                value.push(index + 1);
            }
            return value;
        }, errorItemData);
        errorItemData = Array.from(new Set(errorItemData)).sort((a, b) => a - b);
        if (errorItemData.length !== 0) {
            $NG.alert(`第 ${errorItemData.join("、")} 行，数据不符合规范。请查看规格、单位、分类是否有字段为空 或者 未匹配物料！`);
            return false;
        } else {
            return true;
        }
    }, "check");

    //按钮隐藏
    // $NG.getCmpApi("toolbar_top").hideButton("addrow");
    const btn_arr = ["p_form_equipment_chg_impl", "p_form_equipment_chg_svc", "p_form_equipment_chg_rd", "p_form_equipment_chg_d"];
    btn_arr.forEach((item) => {
        //   console.log(item, $NG.getCmpApi(item));
        //   $NG
        //     .getCmpApi("toolbar_" + item)
        //     .getItem("addrow")
        //     .setHidden();
        //   $NG
        //     .getCmpApi("toolbar_" + item)
        //     .getItem("deleterow")
        //     .setHidden();
        if (item == "p_form_equipment_chg_d") {
            // $NG
            //   .getCmpApi("toolbar_" + item)
            //   .getItem("attachment")
            //   .setHidden();
        }
    });

    function hiddenOriKey(bool) {
        const cellKeys = ["Cell168", "Cell169", "Cell175", "Cell176"];
        cellKeys.forEach((cellKey) => {
            $NG.updateUI((updater) => {
                console.log(`updater`, updater);
                const cell = updater.editGrid.p_form_equipment_chg_d[cellKey];
                if (cell) {
                    for (let key in cell) {
                        if (key.includes("ori")) {
                            cell[key].setProps({
                                hidden: bool,
                            });
                        }
                    }
                }
            });
        });
    }

    const project_amt = {
        _amt: 0,
        //变更含税
        _amt_bg: 0,
        //未税
        _amt_ws: 0,
        sum: function () {
            $NG.updateState((updater) => {
                updater.data.p_form_equipment_chg.setProps({
                    u_total_cost_amt_vat: this._amt,
                    u_total_cost_amt: this._amt_ws,
                    // u_total_cost_change: this._amt_bg,
                });
            });
        },
        set amt(value) {
            this._amt = Number(value);
            this.sum();
        },
        get amt() {
            return this._amt;
        },
        set amt_bg(value) {
            this._amt_bg = Number(value);
            this.sum();
        },
        get amt_bg() {
            return this._amt_bg;
        },
        set amt_ws(value) {
            this._amt_ws = Number(value);
            this.sum();
        },
        get amt_ws() {
            return this.amt_ws;
        },
    };

    ////////////////////////////////////////////////////////////--mstform

    if (mstform) {
        //隐藏页签
        filterQzTable();
        getPtInfoByPhid();
        cntMFilter();
        mstformUpdateUI();
        if (page.oType == "add") {
            mstform.getItem("u_alter_type").setValue("1");

            $NG
                .getCompMap()
                .get("__Tabs__")[0]
                .getApi()
                .updateItems((innerItems, activeKey) => {
                    return [...innerItems.filter((item) => item.key !== "TabPage5")];
                });
            getCntCount("p_form_equipment_chg", "u_cnt_id", () => {
                getCntMInfoByPhid();
                // getSbqdDetailByCnt();
                danjvchaxun();
            });
        }

        const isNeedInit = ["add", "edit", "copy"].includes(page.oType);
        if (isNeedInit) {
            const billNameItem = mstform.getItem("bill_name");
            if (!billNameItem.getValue()) {
                billNameItem.setValue("设备清单变更");
            }
            getEqOri();
        }

        useValuesChange(({ args }) => {
            //   console.log(`项目监听`, args);
            getEqOri();
            getPtInfoByPhid();
            getCntCount("p_form_equipment_chg", "u_cnt_id", () => {
                getCntMInfoByPhid();
                // getSbqdDetailByCnt();
            });
            cntMFilter();
            danjvchaxun();
            getSbqdTotalGapAmt();
        }, "p_form_equipment_chg.phid_pc");

        //监听合同
        useValuesChange(({ args }) => {
            //   console.log(`合同监听`, args);
            getCntMInfoByPhid();
        }, "p_form_equipment_chg_impl.u_cnt_id");
        useValuesChange(({ args }) => {
            //   console.log("测试测试", mstform.getItem("u_alter_type").getValue());
            filterQzTable();
        }, "p_form_equipment_chg.u_alter_type");
    }

    if (dgrid1) {
        const duplicateMap = new Map();
        dgrid1UpdateUI();
        cntDFilter();

        let isCalculating = false; //防止循环的标志

        //合同明细
        registerCalcGroup({
            dataKey: "p_form_equipment_chg_d",
            qtyField: "u_qty",
            taxRateField: "u_cnt_item_tax_rate",
            prcField: "u_cnt_prc",
            prcVatField: "u_cnt_prc_vat",
            amtField: "u_cnt_amt",
            amtVatField: "u_cnt_amt_vat",
        });

        // 拟分包
        registerCalcGroup({
            dataKey: "p_form_equipment_chg_d",
            qtyField: "u_sub_qty",
            taxRateField: "u_sub_tax_rate",
            prcField: "u_sub_prc",
            prcVatField: "u_sub_prc_vat",
            amtField: "u_sub_cost",
            amtVatField: "u_sub_cost_vat",
        });

        //拟采购
        registerCalcGroup({
            dataKey: "p_form_equipment_chg_d",
            qtyField: "u_pur_qty",
            taxRateField: "u_pur_tax_rate",
            prcField: "u_pur_prc",
            prcVatField: "u_pur_prc_vat",
            amtField: "u_pur_cost",
            amtVatField: "u_pur_cost_vat",
        });

        //拟自制
        registerCalcGroup({
            dataKey: "p_form_equipment_chg_d",
            qtyField: "u_self_qty",
            taxRateField: "u_self_tax_rate",
            prcField: "u_self_prc",
            prcVatField: "u_self_prc_vat",
            amtField: "u_self_cost",
            amtVatField: "u_self_cost_vat",
        });

        useDataIndexChange(async ({ args, instance }) => {
            console.log(`触发监听:useDataIndexChange`);
            const record = args[0];
            const details = dgrid1.getData();
            if (record.u_cnt_item) {
                await detectUniqueContractList(details);
                await getCntDInfoByPhid(record, duplicateMap);
            }
            sumGridToForm();
        }, "p_form_equipment_chg_d.u_cnt_item");

        const specs = ['u_sub_spec', 'u_pur_spec']

        useDataIndexChange(async ({ args }) => {
            const temp = await isToCgsq(args[0].u_source_phid)
            if (!temp) {
                $NG.alert("当前明细已经发生了采购下推，不能改变规格型号，请删除相关业务后变更！")
                args[0].u_sub_spec = args[0].u_sub_spec_ori
            }
        }, "u_sub_spec")

        useUpdateRow(({ args }) => {
            const _data = args[0];
            matchingWl(_data);
            _data.done = false;

            dgrid1.refreshView();
        }, "p_form_equipment_chg_d");

        useUpdateRow(async ({ args, table }) => {
            console.log(`触发监听:useUpdateRow`);
            const items = args[0];

            if (!items.u_change_type) {
                items.u_change_type = "1";
            }

            // 查询数据是否有变更

            let changedFields = [];

            let changed = Object.keys(items).some((key) => {
                if (key.endsWith("_ori")) {
                    let originalKey = key.slice(0, -4);
                    let ori = items[key];
                    let now = items[originalKey];

                    let bothEmpty = (ori == null || ori === "") && (now == null || now === "");

                    if (!bothEmpty && ori != now) {
                        changedFields.push(originalKey); // 记录变更字段
                        return true;
                    }
                }
                return false;
            });

            items.u_status = changed ? "1" : "0";

            changedFields.forEach((field) => {
                const el = document.getElementById(field);
                if (el) {
                    el.style.color = "red"; // 字体变红
                    // 或者边框变红
                    // el.style.border = "1px solid red";
                }
            });

            // 你可以打印看看哪些字段变了：
            console.log("变更的字段有：", changedFields);

            table.updateRow(items);
        }, "p_form_equipment_chg_d");

        function isEffectivelyEmpty(val) {
            return val === null || val === undefined || val === "";
        }

        // 检查下推数据
        function staticData(args) {
            let lock = true
            args.forEach((item, index) => {
                if (item.u_sub_name != item.u_sub_name_ori ||
                    item.u_sub_item_msunit != item.u_sub_item_msunit_ori ||
                    item.u_sub_spec != item.u_sub_spec_ori ||
                    item.u_sub_item_category != item.u_sub_item_category_ori ||

                    item.u_pur_name != item.u_pur_name_ori ||
                    item.u_pur_item_msunit != item.u_pur_item_msunit_ori ||
                    item.u_pur_spec != item.u_pur_spec_ori ||
                    item.u_pur_item_category != item.u_pur_item_category_ori ||

                    item.u_self_name != item.u_self_name_ori ||
                    item.u_self_item_msunit != item.u_self_item_msunit_ori ||
                    item.u_self_spec != item.u_self_spec_ori ||
                    item.u_self_item_category != item.u_self_item_category_ori
                ) {
                    switch (item.is_in_form) {
                        case 1:
                            $NG.alert(`${index + 1}行，当前设备清单明细已推送ERP出库，请勿变更物料参数，或者删除下游单据后变更！`)
                            lock = false
                            break
                        case 2:
                            $NG.alert(`${index + 1}行，当前设备清单明细已推送采购申请，请勿变更物料参数，或者删除下游单据后变更！`)
                            lock = false
                            break
                        case 3:
                            $NG.alert(`${index + 1}行，当前设备清单明细已推送采购申请和ERP出库，请勿变更物料参数，或者删除下游单据后变更！`)
                            lock = false
                            break
                    }
                }
            })
            return lock
        }

        useUpdateRows(async ({ args }) => {
            console.log(`触发监听:useUpdateRows`);
            await isInForm(args[0])
            const _arr = args[0];
            // 校验数量变更是否合法合规
            staticData(args[0])
            // 拟采购数量
            _arr.forEach((item) => {
                if (-(Number(item.u_pur_qty_ori) || 0) + (Number(item.u_pur_qty) || 0) + (Number(item.u_rest_qty) || 0) < 0) {
                    $NG.alert(`当前拟采购数量变更不合法,剩余数量仅剩 ${Number(item.u_rest_qty) || 0}`);
                    item.u_pur_qty = item.u_pur_qty_ori;
                }
                if (-(Number(item.u_self_qty_ori) || 0) + (Number(item.u_self_qty) || 0) + (Number(item.u_nzz_rest_qty) || 0) < 0) {
                    item.u_self_qty = item.u_self_qty_ori;
                    $NG.alert(`当前拟自制数量变更不合法,剩余数量仅剩 ${Number(item.u_rest_qty) || 0}`);
                }
            });

            generate15DigitNumber(_arr);
            createSbqdNo(_arr);
            sumGridToForm();
        }, "p_form_equipment_chg_d");

        function cntDFilter() {
            $NG.updateUI((updater) =>
                updater.editGrid.p_form_equipment_chg_d.Cell168.u_cnt_item.setProps((p) => {
                    return {
                        ...p,
                        editor: {
                            ...p.editor,
                            clientSqlFilter: {
                                pphid: mstform.getItem("u_cnt_id").getValue() || 0,
                            },
                        },
                    };
                })
            );
        }

        // 合同清单 唯一性检测
        async function detectUniqueContractList(details) {
            console.log("触发方法 detectUniqueContractList");

            duplicateMap.clear(); // 清空原有的 Map

            details.forEach((rec) => {
                const key = rec.u_cnt_item_no;
                if (key) {
                    duplicateMap.set(key, (duplicateMap.get(key) || 0) + 1);
                }
            });
            // console.log("duplicateMap:", duplicateMap);
        }

        //根据 合同ID 获取 合同清单信息
        async function getCntDInfoByPhid(record, duplicateMap) {
            const res = await $NG.execServer("getCntDInfoByPhid", { cnd_id: mstform.getItem("u_cnt_id").getValue(), phid: record.u_cnt_item });
            // console.log("getCntDInfoByPhid:", res);
            if (res.count > 0) {
                const data = JSON.parse(res.data)[0].extendObjects;
                record.u_cnt_item_no = data.item_no; //合同清单编码
                record.u_eq_item_name = data.item_name;
                record.u_spec = data.user_ggxh; //规格型号
                record.u_msunit = data.unit_phid;
                record.u_msunit_EXName = data.unit_name; //计量单位
                record.u_tech_params = data.user_jscs; //技术参数
                record.u_pc_subitem_category = data.user_gcfxfl; //工程分项分类
                record.u_qty = data.qty; //数量
                // 判断：只有当该 item_no 只出现过一次才允许赋值数量等
                if (!duplicateMap.get(record.u_cnt_item_no)) {
                    record.u_cnt_item_tax_rate = data.taxrate; //税率
                    record.u_cnt_prc_vat = data.prc_vat_fc; //含税单价
                    record.u_cnt_prc = data.prc_fc; //未税单价
                    record.u_cnt_amt_vat = data.amt_vat_fc; //含税金额
                    record.u_cnt_amt = data.amt_fc; //未税金额
                } else {
                    record.u_cnt_item_tax_rate = 0; //税率
                    record.u_cnt_prc_vat = 0; //含税单价
                    record.u_cnt_prc = 0; //未税单价
                    record.u_cnt_amt_vat = 0; //含税金额
                    record.u_cnt_amt = 0; //未税金额
                }
            }
            dgrid1.refreshView();
        }

        function dgrid1UpdateUI(params) {
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_equipment_chg_d.Cell168.setProps({
                    headerStyle: {
                        backgroundColor: "#e5e5e5",
                    },
                });
            });
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_equipment_chg_d.Cell175.setProps({
                    headerStyle: {
                        backgroundColor: "#e5e5e5",
                    },
                });
            });
        }
    }

    if (dgrid2) {
        useUpdateRows(({ args }) => {
            const items = args[0];
            generate15DigitNumber(items);
            sumGridToForm();
        }, "p_form_equipment_chg_impl");
    }

    if (dgrid3) {
        useUpdateRows(({ args }) => {
            const items = args[0];
            generate15DigitNumber(items);
            sumGridToForm();
        }, "p_form_equipment_chg_svc");
    }

    if (dgrid4) {
        useUpdateRows(({ args }) => {
            const items = args[0];
            generate15DigitNumber(items);
            sumGridToForm();
        }, "p_form_equipment_chg_rd");
    }


    // 明细合计
    function sumGridToForm() {
        console.log(`开始`);
        // 安全转换函数
        const toNum = (val) => parseFloat(val || 0);
        // 成本明细差额
        let u_sub_cost_amt_gap = 0;
        let u_sub_cost_amt_vat_gap = 0;
        let u_pur_cost_amt_gap = 0;
        let u_pur_cost_amt_vat_gap = 0;
        let u_self_cost_amt_gap = 0;
        let u_self_cost_amt_vat_gap = 0;

        // 费用预算差额
        let u_implement_amt_vat_gap = 0;
        let u_svc_cost_amt_vat_gap = 0;
        let u_sec_dev_amt_gap = 0;

        // 总成本差额
        let u_total_cost_change = 0;
        let u_total_cost_change_vat = 0;

        // 合同差额
        let u_cnt_amt_chg = 0;
        let u_cnt_amt_vat_chg = 0;

        //原数据
        let u_sub_cost_amt_ori = mstform.getItem("u_sub_cost_amt_ori").getValue() || 0;
        let u_sub_cost_amt_vat_ori = mstform.getItem("u_sub_cost_amt_vat_ori").getValue() || 0;
        let u_pur_cost_amt_ori = mstform.getItem("u_pur_cost_amt_ori").getValue() || 0;
        let u_pur_cost_amt_vat_ori = mstform.getItem("u_pur_cost_amt_vat_ori").getValue() || 0;
        let u_self_cost_amt_ori = mstform.getItem("u_self_cost_amt_ori").getValue() || 0;
        let u_self_cost_amt_vat_ori = mstform.getItem("u_self_cost_amt_vat_ori").getValue() || 0;

        let u_implement_amt_vat_ori = mstform.getItem("u_implement_amt_vat_ori").getValue() || 0;
        let u_svc_cost_amt_vat_ori = mstform.getItem("u_svc_cost_amt_vat_ori").getValue();
        let u_sec_dev_amt_ori = mstform.getItem("u_sec_dev_amt_ori").getValue();

        let u_total_cost_amt_ori = mstform.getItem("u_total_cost_amt_ori").getValue() || 0;
        let u_total_cost_amt_vat_ori = mstform.getItem("u_total_cost_amt_vat_ori").getValue() || 0;

        let u_cnt_amt_ori = mstform.getItem("u_cnt_amt_ori").getValue() || 0;
        let u_cnt_amt_vat_ori = mstform.getItem("u_cnt_amt_vat_ori").getValue() || 0;

        let u_revenue_cost_gm_ori = mstform.getItem("u_revenue_cost_gm_ori").getValue() || 0;
        let u_signed_gm_rate_ori = mstform.getItem("u_signed_gm_rate_ori").getValue() || 0;
        let u_bid_gm_rate_ori = mstform.getItem("u_bid_gm_rate_ori").getValue() || 0;

        let u_win_bid_svc_amt = mstform.getItem("u_win_bid_svc_amt").getValue() || 0;

        // 清单成本
        let u_eq_cost_ori = u_sub_cost_amt_ori + u_pur_cost_amt_ori + u_self_cost_amt_ori;
        let u_eq_cost_vat_ori = u_sub_cost_amt_vat_ori + u_pur_cost_amt_vat_ori + u_self_cost_amt_vat_ori;

        dgrid1.getData().forEach((items, index) => {
            u_sub_cost_amt_gap += toNum(items.u_sub_cost) - toNum(items.u_sub_cost_ori);
            u_sub_cost_amt_vat_gap += toNum(items.u_sub_cost_vat) - toNum(items.u_sub_cost_vat_ori);
            u_pur_cost_amt_gap += toNum(items.u_pur_cost) - toNum(items.u_pur_cost_ori);
            u_pur_cost_amt_vat_gap += toNum(items.u_pur_cost_vat) - toNum(items.u_pur_cost_vat_ori);
            u_self_cost_amt_gap += toNum(items.u_self_cost) - toNum(items.u_self_cost_ori);
            u_self_cost_amt_vat_gap += toNum(items.u_self_cost_vat) - toNum(items.u_self_cost_vat_ori);

            u_cnt_amt_chg += toNum(items.u_cnt_amt) - toNum(items.u_cnt_amt_ori);
            console.log(`第${index}行`, items.u_cnt_amt_vat, items.u_cnt_amt_vat_ori, toNum(items.u_cnt_amt_vat) - toNum(items.u_cnt_amt_vat_ori), u_cnt_amt_vat_chg);
            u_cnt_amt_vat_chg += toNum(items.u_cnt_amt_vat) - toNum(items.u_cnt_amt_vat_ori);
        });
        dgrid2.getData().forEach((items) => {
            u_implement_amt_vat_gap += toNum(items.u_total_impl_amt) - toNum(items.u_total_impl_amt_ori);
        });
        dgrid3.getData().forEach((items) => {
            u_svc_cost_amt_vat_gap += toNum(items.u_total_svc_amt) - toNum(items.u_total_svc_amt_ori);
        });
        dgrid4.getData().forEach((items) => {
            u_sec_dev_amt_gap += toNum(items.u_rd_expenses) - toNum(items.u_rd_expenses_ori);
        });

        u_total_cost_change = u_sub_cost_amt_gap + u_pur_cost_amt_gap + u_self_cost_amt_gap + u_implement_amt_vat_gap + u_svc_cost_amt_vat_gap + u_sec_dev_amt_gap;
        u_total_cost_change_vat = u_sub_cost_amt_vat_gap + u_pur_cost_amt_vat_gap + u_self_cost_amt_vat_gap + u_implement_amt_vat_gap + u_svc_cost_amt_vat_gap + u_sec_dev_amt_gap;

        let u_eq_cost_chg = u_sub_cost_amt_gap + u_pur_cost_amt_gap + u_self_cost_amt_gap;
        let u_eq_cost_vat_chg = u_sub_cost_amt_vat_gap + u_pur_cost_amt_vat_gap + u_self_cost_amt_vat_gap;
        let u_eq_cost = u_eq_cost_ori + u_eq_cost_chg;
        let u_eq_cost_vat = u_eq_cost_vat_ori + u_eq_cost_vat_chg;

        $NG.updateState((updater) => {
            updater.data.p_form_equipment_chg.setProps({
                // 成本明细
                u_sub_cost_amt_gap: u_sub_cost_amt_gap,
                u_sub_cost_amt_vat_gap: u_sub_cost_amt_vat_gap,
                u_sub_cost_amt: u_sub_cost_amt_ori + u_sub_cost_amt_gap,
                u_sub_cost_amt_vat: u_sub_cost_amt_vat_ori + u_sub_cost_amt_vat_gap,
                u_sub_cost_ratio: (u_sub_cost_amt_ori + u_sub_cost_amt_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                u_pur_cost_amt_gap: u_pur_cost_amt_gap,
                u_pur_cost_amt_vat_gap: u_pur_cost_amt_vat_gap,
                u_pur_cost_amt: u_pur_cost_amt_ori + u_pur_cost_amt_gap,
                u_pur_cost_amt_vat: u_pur_cost_amt_vat_ori + u_pur_cost_amt_vat_gap,
                u_pur_cost_ratio: (u_pur_cost_amt_ori + u_pur_cost_amt_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                u_self_cost_amt_gap: u_self_cost_amt_gap,
                u_self_cost_amt_vat_gap: u_self_cost_amt_vat_gap,
                u_self_cost_amt: u_self_cost_amt_ori + u_self_cost_amt_gap,
                u_self_cost_amt_vat: u_self_cost_amt_vat_ori + u_self_cost_amt_vat_gap,
                u_self_cost_ratio: (u_self_cost_amt_ori + u_self_cost_amt_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                // 费用
                u_implement_amt_vat_gap: u_implement_amt_vat_gap,
                u_implement_amt_vat: u_implement_amt_vat_ori + u_implement_amt_vat_gap,
                u_implement_cost_ratio: (u_implement_amt_vat_ori + u_implement_amt_vat_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                u_svc_cost_amt_vat_gap: u_svc_cost_amt_vat_gap,
                u_svc_cost_amt_vat: u_svc_cost_amt_vat_ori + u_svc_cost_amt_vat_gap,
                u_svc_cost_ratio: (u_svc_cost_amt_vat_ori + u_svc_cost_amt_vat_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                u_sec_dev_amt_gap: u_sec_dev_amt_gap,
                u_sec_dev_amt: u_sec_dev_amt_ori + u_sec_dev_amt_gap,
                u_sec_dev_ratio: (u_sec_dev_amt_ori + u_sec_dev_amt_gap) / (u_total_cost_amt_ori + u_total_cost_change),

                // 总成本
                u_eq_cost_ori: u_eq_cost_ori,
                u_eq_cost_vat_ori: u_eq_cost_vat_ori,
                u_eq_cost_chg: u_eq_cost_chg,
                u_eq_cost_vat_chg: u_eq_cost_vat_chg,
                u_eq_cost: u_eq_cost,
                u_eq_cost_vat: u_eq_cost_vat,

                u_total_cost_change: u_total_cost_change,
                u_total_cost_amt: u_total_cost_amt_ori + u_total_cost_change,
                u_total_cost_change_vat: u_total_cost_change_vat,
                u_total_cost_amt_vat: u_total_cost_amt_vat_ori + u_total_cost_change_vat,

                // 累计清单成本
                u_eq_cost_chg_sum: ((Number(window._catch_eq_totalAmt.eq_total_amt) || 0) + u_total_cost_change).toFixed(2),
                u_eq_cost_vat_chg_sum: ((Number(window._catch_eq_totalAmt.eq_total_amt_vat) || 0) + u_total_cost_change_vat).toFixed(2),

                // 合同
                u_cnt_amt_chg: u_cnt_amt_chg,
                u_cnt_amt_vat_chg: u_cnt_amt_vat_chg,
                u_cnt_amt: u_cnt_amt_ori + u_cnt_amt_chg,
                u_cnt_amt_vat: u_cnt_amt_vat_ori + u_cnt_amt_vat_chg,

                // 毛利
                u_revenue_cost_gm_chg: u_cnt_amt_chg - u_total_cost_change,
                u_revenue_cost_gm: u_cnt_amt_chg - u_total_cost_change + u_revenue_cost_gm_ori,
                // 本次合同变更未税  项目成本  变更前收入成本   原服务  服务成本含税 + 变更前合同未税  - 本次变更合同未税
                // u_signed_gm_rate: (u_cnt_amt_chg - u_total_cost_change + u_revenue_cost_gm_ori + (u_svc_cost_amt_vat_ori + u_svc_cost_amt_vat_gap)) / (u_cnt_amt_ori + u_cnt_amt_chg),// 0617前计算逻辑
                u_signed_gm_rate: (u_cnt_amt_ori + u_cnt_amt_chg -
                    (u_sub_cost_amt_ori + u_sub_cost_amt_gap) -
                    (u_pur_cost_amt_ori + u_pur_cost_amt_gap) -
                    (u_self_cost_amt_ori + u_self_cost_amt_gap) -

                    (u_win_bid_svc_amt) -
                    (u_implement_amt_vat_ori + u_implement_amt_vat_gap) - (u_sec_dev_amt_ori - u_sec_dev_amt_gap)) / (u_cnt_amt_ori + u_cnt_amt_chg),
                u_signed_gm_rate_chg: (u_cnt_amt_chg - u_total_cost_change + u_revenue_cost_gm_ori + (u_svc_cost_amt_vat_ori + u_svc_cost_amt_vat_gap)) / (u_cnt_amt_ori + u_cnt_amt_chg) - u_signed_gm_rate_ori,
                u_bid_gm_rate: (u_cnt_amt_chg - u_total_cost_change + u_revenue_cost_gm_ori) / (u_cnt_amt_ori + u_cnt_amt_chg),
                u_bid_gm_rate_chg: (u_cnt_amt_chg - u_total_cost_change + u_revenue_cost_gm_ori) / (u_cnt_amt_ori + u_cnt_amt_chg) - u_bid_gm_rate_ori,
                // 中标服务费率
                u_svc_amt_rate: u_win_bid_svc_amt / (u_total_cost_amt_ori + u_total_cost_change),
            });
            console.log(`成本测试`, u_cnt_amt_ori + u_cnt_amt_chg,
                (u_sub_cost_amt_ori + u_sub_cost_amt_gap),
                (u_pur_cost_amt_ori + u_pur_cost_amt_gap),
                (u_self_cost_amt_ori + u_self_cost_amt_gap),
                (u_implement_amt_vat_ori + u_implement_amt_vat_gap),
                (u_svc_cost_amt_vat_ori + u_svc_cost_amt_vat_gap));
        });
    }

    //深化数量
    let shsj_Lock = 0;
    function shsjQty(el) {
        if (shsj_Lock) {
            clearTimeout(shsj_Lock);
            shsj_Lock = 0;
        }
        shsj_Lock = setTimeout(() => {
            $NG.execServer("getCurrentShsjQtyBySbqd", { phid: el.u_source_phid }, (res) => {
                console.log(`深化`, res);
                if (res.count == 0) return;
                const _data = JSON.parse(res.data)[0].extendObjects;
                if (el.u_qty < (Number(_data.qty) || 0)) {
                    $NG.alert(`警告：深化设计已经深化${_data.qty}个，请确保深化数量小于等于当前数量`);
                    el.u_qty = _data.qty;
                    dgrid1.refreshView();
                }
            });
            shsj_Lock = 0;
        }, 1500);
    }
    // 采购申请数量
    async function isToCgsq(source_phid) {
        let lock = true
        await $NG.execServer("getCurrentCgsqQtySbqd", { phid: source_phid }, (res) => {
            if (res.count == 0) {
                lock = true
            } else {
                lock = false
            }
        });
        return true
    }
    // 分包招标计划数量
    function fbzbJhQty(el) {
        $NG.execServer("getCurrentFbzbQtyBySbqd", { phid: el.u_source_phid }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (el.u_sub_qty < (Number(_data.qty) || 0)) {
                $NG.alert(`警告：分包招标计划已申请${_data.qty}个，请确保招标数量小于等于当前数量`);
                el.u_sub_qty = _data.qty;
                dgrid1.refreshView();
            }
        });
    }
    // 采购申请数量
    function cgsqQty(el) {
        $NG.execServer("getCurrentCgsqQtySbqd", { phid: el.u_source_phid }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (el.u_pur_qty < (Number(_data.qty) || 0)) {
                $NG.alert(`警告：采购申请已申请${_data.qty}个，请确保招标数量小于等于当前数量`);
                el.u_pur_qty = _data.qty;
                dgrid1.refreshView();
            }
        });
    }
    // 产品出库数量
    function cpckQty(el) {
        $NG.execServer("getCurrentCpckQtyBySbqd", { phid: el.u_source_phid }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (el.u_pur_qty < (Number(_data.qty) || 0)) {
                $NG.alert(`警告：产品出库已出库${_data.qty}个，请确保出库数量小于等于当前数量`);
                el.u_pur_qty = _data.qty;
                dgrid1.refreshView();
            }
        });
    }

    //这里标识这些字段只要发生编辑，就让u_item_no变成null，用于匹配物料判断
    const editNfbKey = ["u_sub_name", "u_sub_spec", "u_sub_item_category", "u_sub_item_msunit"];
    const editNcg = ["u_pur_item_msunit", "u_pur_name", "u_pur_spec", "u_pur_item_category"];
    const editNzz = ["u_self_item_msunit", "u_self_name", "u_self_spec", "u_self_item_category"];
    editNfbKey.forEach((key) => {
        useDataIndexChange(({ args }) => {
            args[0].u_sub_item = null;
            dgrid1.refreshView();
        }, key);
    });
    editNcg.forEach((key) => {
        useDataIndexChange(({ args }) => {
            args[0].u_pur_item = null;
            dgrid1.refreshView();
        }, key);
    });
    editNzz.forEach((key) => {
        useDataIndexChange(({ args }) => {
            args[0].u_self_item = null;
            dgrid1.refreshView();
        }, key);
    });

    // 隐藏标签
    function filterQzTable() {
        if (mstform.getItem("u_alter_type").getValue() == "2") {
            $NG
                .getCompMap()
                .get("__Tabs__")[0]
                .getApi()
                .updateItems((innerItems, activeKey) => {
                    return [...innerItems.filter((item) => true)];
                });
            // getQzInfo();
            dgrid5 = $NG.getCmpApi("p_form_equipment_chg_qz");

            registerCalcGroup({
                dataKey: "p_form_equipment_chg_qz",
                qtyField: "u_qty",
                taxRateField: "u_rate",
                prcField: "u_cnt_prc",
                prcVatField: "u_cnt_prc_vat",
                amtField: "u_cnt_amt",
                amtVatField: "u_cnt_amt_vat",
            });

            useUpdateRows(({ args }) => {
                dgrid5 = $NG.getCmpApi("p_form_equipment_chg_qz");
                const _arr = args[0];
                //   console.log("测试");
                //拿到来源id最大的编码
                _arr.forEach((item) => {
                    if (!item.u_source_phid && !item.u_cnt_no) {
                        item.u_cnt_no = "QZ-" + generate15DigitNumber();
                    }
                    // item.u_cnt_prc_vat = (Number(item.u_cnt_prc) || 0) * ((Number(item.u_rate) || 0) + 1);
                    // item.u_cnt_amt = (Number(item.u_qty) || 0) * (Number(item.u_cnt_prc) || 0);
                    // item.u_cnt_amt_vat = (Number(item.u_cnt_prc_vat) || 0) * (Number(item.u_qty) || 0);
                });
                dgrid5.refreshView();
                setTimeout(() => {
                    qzInfoToSbqdInfo();
                    sumGridToForm();
                }, 300);
                dgrid5.refreshView();
                dgrid1.refreshView();
            }, "p_form_equipment_chg_qz");
        } else if (mstform.getItem("u_alter_type").getValue() == "1") {
            $NG
                .getCompMap()
                .get("__Tabs__")[0]
                .getApi()
                .updateItems((innerItems, activeKey) => {
                    return [...innerItems.filter((item) => item.key !== "TabPage5")];
                });
        }
    }

    function mstformUpdateUI(params) {
        //   console.log("mstformUpdateUI");

        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_chg.u_eq_ori.setProps({
                onDoubleClick() {
                    var u_eq_ori = mstform.getItem("u_eq_ori").getValue();
                    if (u_eq_ori) {
                        const { origin, pathname } = window.location;
                        const hash = `#/customform/detail?id=${u_eq_ori}&otype=view&busType=EFORM9000000031&isSso=1`; // 路径
                        $NG.open(`${origin}${pathname}${hash}`, { AppTitle: "设备清单" });
                        // }
                    }
                },
            });
        });
    }

    // 明细监听单元格的函数
    function registerCalcGroup({ dataKey, qtyField, taxRateField, prcField, prcVatField, amtField, amtVatField }) {
        let isCalculating = false;

        // 数量变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${qtyField}`);

        // 税率变动 计算未税单价和未税金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;
            const taxRate = parseFloat(args[0][taxRateField] || 0);
            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + taxRate);
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);

            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${taxRateField}`);

        // 未税单价变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;
            const taxRate = parseFloat(args[0][taxRateField] || 0);
            args[0][prcVatField] = (args[0][prcField] || 0) * (1 + taxRate);
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);

            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${prcField}`);

        // 含税单价变动：重新计算金额
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;
            const taxRate = parseFloat(args[0][taxRateField] || 0);
            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + taxRate);
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${prcVatField}`);

        // 未税金额变动：反算单价
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            const qty = args[0][qtyField] || 0;
            const taxRate = parseFloat(args[0][taxRateField] || 0);
            args[0][prcField] = qty !== 0 ? args[0][amtField] / qty : 0;
            args[0][prcVatField] = (args[0][prcField] || 0) * (1 + taxRate);
            args[0][amtVatField] = (args[0][qtyField] || 0) * (args[0][prcVatField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${amtField}`);

        // 含税金额变化
        useDataIndexChange(({ args, instance }) => {
            if (isCalculating) return;
            isCalculating = true;

            const qty = args[0][qtyField] || 0;
            const taxRate = parseFloat(args[0][taxRateField] || 0);
            args[0][prcVatField] = qty !== 0 ? args[0][amtVatField] / qty : 0;
            args[0][prcField] = (args[0][prcVatField] || 0) / (1 + taxRate);
            args[0][amtField] = (args[0][qtyField] || 0) * (args[0][prcField] || 0);
            instance.updateRow(args[0]);

            isCalculating = false;
        }, `${dataKey}.${amtVatField}`);
    }

    // function totalSum(data, table) {
    //   // 触发了锁，等待解锁
    //   //   console.log(`当前锁状态`,onLock);
    //   while (!onLock) {}
    //   onLock = false;
    //   const _arr = data;
    //   switch (table) {
    //     case "p_form_equipment_chg_d":
    //       //含税成本
    //       nfb_amt_vat = 0;
    //       ncg_amt_vat = 0;
    //       nzz_amt_vat = 0;
    //       //未税成本
    //       nfb_amt = 0;
    //       ncg_amt = 0;
    //       nzz_amt = 0;
    //       // 合同
    //       cnt_amt = 0;
    //       cnt_amt_vat = 0;
    //       break;
    //     case "p_form_equipment_chg_impl":
    //       ss_amt = 0;
    //       break;
    //     case "p_form_equipment_chg_svc":
    //       cg_amt = 0;
    //       break;
    //     case "p_form_equipment_chg_rd":
    //       zz_amt = 0;
    //       zz_amt_ori = 0;
    //       break;
    //   }
    //   _arr.forEach((item) => {
    //     item.u_bglx = "normal";
    //     //汇总表头
    //     switch (table) {
    //       case "p_form_equipment_chg_d":
    //         item.u_pur_cost_vat = (Number(item.u_pur_prc_vat) || 0) * (Number(item.u_pur_qty) || 0);
    //         item.u_self_cost_vat = (Number(item.u_self_prc_vat) || 0) * (Number(item.u_self_qty) || 0);
    //         item.u_cnt_amt = (Number(item.u_qty) || 0) * (Number(item.u_cnt_prc) || 0);
    //         item.u_cnt_amt_vat = (Number(item.u_qty) || 0) * (Number(item.u_cnt_prc_vat) || 0);
    //         //含税成本
    //         ncg_amt_vat += Number(item.u_pur_cost_vat) || 0;
    //         nzz_amt_vat += Number(item.u_self_cost_vat) || 0;
    //         //未税成本
    //         ncg_amt += Number(item.u_pur_cost) || 0;
    //         nzz_amt += Number(item.u_self_cost) || 0;
    //         //合同清单
    //         cnt_amt += Number(item.u_cnt_amt) || 0;
    //         cnt_amt_vat += Number(item.u_cnt_amt_vat) || 0;
    //         break;
    //       case "p_form_equipment_chg_impl":
    //         ss_amt += Number(item.u_total_impl_amt) || 0;
    //         break;
    //       case "p_form_equipment_chg_svc":
    //         cg_amt += Number(item.u_total_svc_amt) || 0;
    //         break;
    //       case "p_form_equipment_chg_rd":
    //         zz_amt += Number(item.u_rd_expenses) || 0;
    //         zz_amt_ori += Number(item.u_rd_expenses_ori) || 0;
    //         break;
    //     }
    //   });
    //   //汇总总额
    //   project_total_amt = nfb_amt_vat + ncg_amt_vat + nzz_amt_vat + ss_amt + cg_amt + zz_amt;
    //   //比例
    //   switch (table) {
    //     case "p_form_equipment_chg_d":
    //       nfb_b = Number(nfb_amt_vat / project_total_amt) || 0;
    //       ncg_b = Number(ncg_amt_vat / project_total_amt) || 0;
    //       nzz_b = Number(nzz_amt_vat / project_total_amt) || 0;
    //       break;
    //     case "p_form_equipment_chg_impl":
    //       ss_b = Number(ss_amt / project_total_amt) || 0;
    //       break;
    //     case "p_form_equipment_chg_svc":
    //       cg_b = Number(cg_amt / project_total_amt) || 0;
    //       break;
    //     case "p_form_equipment_chg_rd":
    //       zz_b = Number(zz_amt / project_total_amt) || 0;
    //       break;
    //   }

    //   setTimeout(() => {
    //     //计算差额
    //     const purgapvat = ncg_amt_vat - mstform.getItem("u_pur_cost_amt_vat_ori").getValue();
    //     const selfgapvat = nzz_amt_vat - mstform.getItem("u_self_cost_amt_vat_ori").getValue();
    //     const putgap = ncg_amt - mstform.getItem("u_pur_cost_amt_ori").getValue();
    //     const selfgap = nzz_amt - mstform.getItem("u_self_cost_amt_ori").getValue();
    //     const fwgapvat = ss_amt - mstform.getItem("u_implement_amt_vat_ori").getValue();
    //     const svcgapvat = cg_amt - mstform.getItem("u_svc_cost_amt_vat_ori").getValue();
    //     const purbgap = ncg_b - mstform.getItem("u_pur_cost_ratio_ori").getValue();
    //     const selfbgap = nzz_b - mstform.getItem("u_self_cost_ratio_ori").getValue();
    //     const ssgap = ss_b - mstform.getItem("u_implement_cost_ratio_ori").getValue();
    //     const svcbgap = cg_b - mstform.getItem("u_svc_cost_ratio_ori").getValue();
    //     const zzgap = zz_amt - zz_amt_ori;
    //     const cntamtgap = cnt_amt - mstform.getItem("u_cnt_amt_ori").getValue();
    //     const cntamtgapvat = cnt_amt_vat - mstform.getItem("u_cnt_amt_vat_ori").getValue();
    //     $NG.updateState((updater) => {
    //       updater.data.p_form_equipment_chg.setProps({
    //         u_pur_cost_amt_vat: ncg_amt_vat,
    //         u_self_cost_amt_vat: nzz_amt_vat,

    //         u_pur_cost_amt: ncg_amt,
    //         u_self_cost_amt: nzz_amt,
    //         u_implement_amt_vat: ss_amt,
    //         u_implement_amt: ss_amt,
    //         u_svc_cost_amt_vat: cg_amt,
    //         u_svc_cost_amt: cg_amt,
    //         u_sec_dev_amt: zz_amt,
    //         u_pur_cost_ratio: ncg_b,
    //         u_self_cost_ratio: nzz_b,

    //         u_implement_cost_ratio: ss_b,
    //         u_svc_cost_ratio: cg_b,
    //         u_sec_dev_ratio: zz_b,

    //         u_implement_amt_vat_gap: fwgapvat,
    //         u_svc_cost_amt_vat_gap: svcgapvat,

    //         u_pur_cost_ratio_gap: purbgap,
    //         u_self_cost_ratio_gap: selfbgap,

    //         u_implement_cost_ratio_gap: ssgap,
    //         u_svc_cost_ratio_gap: svcbgap,
    //         u_sec_dev_amt_gap: zzgap,

    //         // 合同清单相关
    //         u_cnt_amt_chg: cntamtgap,
    //         u_cnt_amt_vat_chg: cntamtgapvat,

    //         u_cnt_amt: (Number(mstform.getItem("u_cnt_amt_ori").getValue()) || 0) + cntamtgap,
    //         u_cnt_amt_vat: (Number(mstform.getItem("u_cnt_amt_vat_ori").getValue()) || 0) + cntamtgapvat,
    //         u_total_cost_amt: (Number(mstform.getItem("u_total_cost_amt_ori").getValue()) || 0) + subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap,
    //         u_total_cost_amt_vat: (Number(mstform.getItem("u_total_cost_amt_vat_ori").getValue()) || 0) + subgapvat + purgapvat + selfgapvat + fwgapvat + svcgapvat + zzgap,
    //         // 毛利
    //         u_revenue_cost_gm_chg: cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap),
    //         u_revenue_cost_gm: cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap) + (Number(mstform.getItem("u_revenue_cost_gm_ori").getValue()) || 0),
    //         u_signed_gm_rate_chg: (cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap)) / cntamtgap,
    //         u_signed_gm_rate: (Number((cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap)) / cntamtgap) || 0) + (Number(mstform.getItem("u_signed_gm_rate_ori").getValue()) || 0),
    //         // 投标u_signed_gm_rate_chg
    //         u_bid_gm_rate_chg: Boolean(cntamtgap) ? (cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap) - (Number(mstform.getItem("u_win_bid_svc_amt").getValue()) || 0)) / cntamtgap : 0,
    //         u_bid_gm_rate: (Boolean(cntamtgap) ? (cntamtgap - (subgap + putgap + selfgap + fwgapvat + svcgapvat + zzgap) - (Number(mstform.getItem("u_win_bid_svc_amt").getValue()) || 0)) / cntamtgap : 0) + (Number(mstform.getItem("u_bid_gm_rate_ori").getValue()) || 0),
    //       });
    //     });
    //   }, 200);
    //   //项目金额变更汇总
    //   project_amt.amt_bg = project_total_amt;
    //   //   console.log(`汇总变更`, project_amt.amt_bg, nfb_amt_vat, ncg_amt_vat, nzz_amt_vat, ss_amt, cg_amt, zz_amt);
    //   onLock = true;
    //   dgrid1.refreshView();
    // }

    //生成明细主键
    function generate15DigitNumber(arr) {
        if (!arr) {
            let str = "";
            // 获取当前时间戳
            let timestamp = Date.now().toString();
            // 如果时间戳不足 15 位，计算需要补充的位数
            let remainingLength = 15 - timestamp.length;
            if (remainingLength > 0) {
                // 生成指定长度的随机数
                let randomPart = "";
                for (let i = 0; i < remainingLength; i++) {
                    randomPart += Math.floor(Math.random() * 10);
                }
                // 将时间戳和随机数拼接成 15 位数字
                str = String(timestamp + randomPart);
            } else {
                // 如果时间戳长度超过 15 位，截取前 15 位
                str = String(timestamp.slice(0, 15));
            }
            return str;
        }

        arr.forEach((item) => {
            let str = "";
            // 获取当前时间戳
            let timestamp = Date.now().toString();
            // 如果时间戳不足 15 位，计算需要补充的位数
            let remainingLength = 15 - timestamp.length;
            if (remainingLength > 0) {
                // 生成指定长度的随机数
                let randomPart = "";
                for (let i = 0; i < remainingLength; i++) {
                    randomPart += Math.floor(Math.random() * 10);
                }
                // 将时间戳和随机数拼接成 15 位数字
                str = String(timestamp + randomPart);
            } else {
                // 如果时间戳长度超过 15 位，截取前 15 位
                str = String(timestamp.slice(0, 15));
            }
            if (!item.u_phid) {
                item.u_phid = str;
                dgrid1.refreshView();
                dgrid2.refreshView();
                dgrid3.refreshView();
                dgrid4.refreshView();
            }
        });
    }

    //生成设备清单编码
    function createSbqdNo(arr) {
        arr.forEach(function (item) {
            if (!item.u_eq_item_no) {
                item.u_eq_item_no = String(Date.now());
            }
        });
    }

    // 获取变更前设备清单信息
    function getEqOri() {
        console.log(`获取原始信息`);
        //   console.log("获取变更前设备清单信息");
        let phid_pc = mstform.getItem("phid_pc").getValue();
        try {
            $NG.execServer("getEqOri", { phid_pc: phid_pc }, function (res) {
                // console.log("getEqOri", res);
                if (res.count > 0) {
                    const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                    console.log("打印功能扩展 getEqOri", data);
                    $NG.updateState((updater) => {
                        updater.data.p_form_equipment_chg.setProps({
                            u_eq_ori: {
                                value: data.phid,
                                label: data.bill_name,
                            },
                            u_cnt_amt_ori: data.u_cnt_amt,
                            u_cnt_amt_vat_ori: data.u_cnt_amt_vat,
                            u_total_cost_amt_ori: data.u_total_cost_amt,
                            u_total_cost_amt_vat_ori: data.u_total_cost_amt_vat,
                            u_revenue_cost_gm_ori: data.u_revenue_cost_gm,
                            u_signed_gm_rate_ori: data.u_signed_gm_rate,
                            u_bid_gm_rate_ori: data.u_bid_gm_rate,

                            u_sub_cost_amt_ori: data.u_sub_cost_amt,
                            u_sub_cost_amt_vat_ori: data.u_sub_cost,
                            u_sub_cost_ratio_ori: data.u_sub_cost_ratio,

                            u_pur_cost_amt_ori: data.u_pur_cost_amt,
                            u_pur_cost_amt_vat_ori: data.u_pur_cost_vat,
                            u_pur_cost_ratio_ori: data.u_pur_cost_ratio,

                            u_self_cost_amt_ori: data.u_self_cost,
                            u_self_cost_amt_vat_ori: data.u_self_cost_vat,
                            u_self_cost_ratio_ori: data.u_self_cost_ratio,

                            u_implement_amt_vat_ori: data.u_implement_amt,
                            u_implement_cost_ratio_ori: data.u_implement_cost_ratio,

                            u_svc_cost_amt_vat_ori: data.u_svc_cost_amt,
                            u_svc_cost_ratio_ori: data.u_svc_cost_ratio,

                            u_sec_dev_amt_ori: data.u_sec_dev_amt,
                            u_sec_dev_ratio_ori: data.u_sec_dev_ratio,

                            u_source_phid: data.phid,
                        });
                    });
                } else {
                    // console.log("功能扩展暂无数据");
                }
            });
        } catch (error) {
            console.error("功能扩展报错:", error);
        }
    }

    //匹配物料请求
    async function getWlRequest(list) {
        const url = window.location.href;
        const protocol = $NG.split(url, "/")[0]; // 协议类型
        const url_domain = $NG.split(url, "/")[2]; // 直接提取域名部分
        const url_path = "/sd/common/interior/createResourceFileSync"; // 路径
        const response = await fetch(`${protocol}//${url_domain}${url_path}`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json", // 设置请求头
            },
            body: JSON.stringify(list),
        });
        // const response = await fetch("https://inner-apisix.hisense.com/hisense/sd/common/interior/createResourceFileSync?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6", {
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json", // 设置请求头
        //   },
        //   body: JSON.stringify(list),
        // });
        const res = await response.json();
        if (res.IsOk) {
            //新增成功
            $NG.message(`保存成功，正在重新校验 90%！`);
            matchingWl(); //重新匹配
            $NG.alert(`匹配物料完成！ 100%`);
        } else {
            if (res.data == "批量新增失败，入参为空！") {
                $NG.alert("匹配完成！");
            } else {
                $NG.alert("匹配错误！");
            }
        }
    }

    // 判断是否存在下游单据
    async function isInForm(rows) {
        const phids = rows.reduce((value, item) => {
            // is_in_form   1:erp   2:采购申请   3:全部推送   4:正常数据
            if (!item.is_in_form && item.u_source_phid) {
                value.push(`'${item.u_source_phid}'`)
            }
            return value
        }, [])
        if (phids.length == 0) return
        await $NG.execServer("getSbqdchgIsincgByphid", { phids: `(${phids.join(',')})` }, async (sqres) => {
            let sqs = []
            let erp = []
            let general = []
            if (sqres.count !== 0) {
                sqs = JSON.parse(sqres.data).reduce((value, items) => {
                    const it = items.extendObjects
                    if (it.user_source_id) {
                        value.push(it.u_source_phid)
                    }
                    return value
                }, [])
            }
            await $NG.execServer("getSbqdchgIsinErpByphid", { phids: `(${phids.join(',')})` }, (erpres) => {
                if (erpres.count !== 0) {
                    erp = JSON.parse(erpres.data).reduce((value, items) => {
                        const it = items.extendObjects
                        if (it.u_source_id) {
                            value.push(it.u_source_phid)
                        }
                        return value
                    }, [])
                }
                if (sqs.length != 0) {
                    rows.forEach(item => {
                        if (sqs.includes(item.user_source_phid)) {
                            item.is_in_form = 2
                        }
                    })
                }
                if (erp.length != 0) {
                    rows.forEach(item => {
                        if (erp.includes(item.u_source_phid)) {
                            item.is_in_form = 1
                        }
                    })
                }
                if (erp.length !== 0 && sqs.length !== 0) {
                    general = sqs.reduce((value, item) => {
                        if (erp.includes(item)) {
                            value.push(item)
                        }
                        return value
                    }, [])
                    if (general.length !== 0) {
                        rows.forEach(item => {
                            if (general.includes(item.u_source_phid)) {
                                item.is_in_form = 3
                            }
                        })
                    }
                }
                let temp = [...sqs, ...erp, ...general]
                temp = Array.from(new Set(temp))
                rows.forEach(item => {
                    if (!temp.includes(item.u_source_phid)) {
                        item.is_in_form = 4
                    }
                })
                dgrid1.refreshView()
            })
        })
    }

    function getPtInfoByPhid() {
        let phidV = mstform.getValues().phid || 0;
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getEQChgCount", { phid_pc: mstform.getItem("phid_pc").getValue(), phid: phidV }, function (res) {
                console.log("打印功能扩展:getEQChgCount", res);
                try {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    if (datas.count == 0) {
                        $NG.updateState((updater) => {
                            updater.data.p_form_equipment_chg.setProps({
                                u_is_init: "1",
                            });
                        });
                    } else {
                        $NG.updateState((updater) => {
                            updater.data.p_form_equipment_chg.setProps({
                                u_is_init: "0",
                            });
                        });
                    }
                } catch (error) {
                    console.error("打印报错:getEQChgCount:", error);
                    $NG.updateState((updater) => {
                        updater.data.p_form_equipment_chg.setProps({
                            u_is_init: "0",
                        });
                    });
                }
            });
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                //   console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_equipment_chg.setProps({
                        //项目编码
                        u_pc_no: datas.pc_no,
                        //项目金额
                        approx_contract_fc: datas.approx_contract_fc,
                        //计划开工日期
                        start_date: datas.start_date,
                        //计划完工日期
                        end_date: datas.end_date,
                        //售前顾问
                        u_sqgw: {
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //项目经理
                        u_project_manager: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //组织
                        phid_org_phid: {
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        //区域中心
                        u_regional_center: {
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        //产品线
                        u_product_line: {
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        //客户名称
                        customer: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        //部门
                        u_dept: {
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        //项目类型
                        u_pc_type: {
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        //项目预算组织编码
                        budget_org_code: datas.budget_org_no,
                        //项目预算组织
                        budget_org_phid: {
                            value: datas.budget_org_phid,
                            label: datas.budget_org_name,
                        },
                        phid_org: {
                            //部门
                            value: datas.org_phid,
                            label: datas.org_name,
                        },
                    });
                });
            });
        }
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_chg.u_cnt_id.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: mstform.getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }

    function getCntMInfoByPhid(params) {
        cntDFilter();
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_id").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            // console.log(datas);
            $NG.updateState((updater) => {
                updater.data.p_form_equipment_chg.setProps({
                    u_cnt_no: datas.pcm_no, //合同编号
                    start_dt: datas.start_dt, //约定开工时间
                    end_dt: datas.end_dt, //约定完工时间
                    u_total_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
                    cnt_sum_vat_fc: datas.cnt_sum_vat_fc, //合同价税合计
                    //产品线
                    user_product_line: {
                        value: datas.midwife_phid,
                        label: datas.midwife_name,
                    },
                    //合同类型
                    u_cnt_type: {
                        value: datas.pct_id,
                        label: datas.pct_name,
                    },
                    //甲方单位
                    u_customer: {
                        value: datas.customer_id,
                        label: datas.customer_name,
                    },
                    //乙方单位
                    supply: {
                        value: datas.supply_id,
                        label: datas.supply_name,
                    },
                    //发票类型
                    u_invoice_type: {
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,
                    },
                    //购方信息（客户信息）（收票单位信息）
                    //单位名称
                    tick_id: {
                        value: datas.tick_id,
                        label: datas.tick_name,
                    },
                    //单位编码
                    tick_no: datas.tick_no,
                    //社会信用代码
                    tick_unisocialcredit: datas.tick_unisocialcredit,
                    //单位地址
                    tick_taxaddress: datas.tick_taxaddress,
                    //联系电话
                    tick_taxtelephone: datas.tick_taxtelephone,
                    //银行名称
                    tick_taxbankid: {
                        value: datas.tick_taxbankid,
                        label: datas.tick_taxbankname,
                    },
                    //银行账号
                    tick_taxaccountno: datas.tick_taxaccountno,
                    //销方信息（供应商信息）（开票单位信息）
                    //单位名称
                    inv_id: { value: datas.inv_id, label: datas.inv_name },
                    //单位编码
                    inv_no: datas.inv_no,
                    //社会信用代码
                    inv_unisocialcredit: datas.inv_unisocialcredit,
                    //单位地址
                    inv_taxaddress: datas.inv_taxaddress,
                    //联系电话
                    inv_taxtelephone: datas.inv_taxtelephone,
                    //银行名称
                    inv_taxbankid: {
                        value: datas.inv_taxbankid,
                        label: datas.inv_taxbankname,
                    },
                    //银行账号
                    inv_taxaccountno: datas.inv_taxaccountno,
                });
            });
            // getQzInfo();
        });
    }

    //判断 arr1 和 arr2 的交集和补集
    function compareArrays(arr1, arr2) {
        const result = [[], [], []];

        // 遍历 arr1，找出 arr1 有但 arr2 没有的元素
        arr1.forEach((item1) => {
            const billNo1 = item1.u_bill_no;
            const isFoundInArr2 = arr2.some((item2) => item2.bill_no == billNo1);

            if (!isFoundInArr2) {
                result[0].push(item1);
            }
        });

        // 遍历 arr2，找出 arr2 有但 arr1 没有的元素
        arr2.forEach((item2) => {
            const billNo2 = item2.bill_no;
            const isFoundInArr1 = arr1.some((item1) => item1.u_bill_no == billNo2);

            if (!isFoundInArr1) {
                result[1].push(item2);
            }
        });
        //   console.log(`测试用例：`, result);
        // 找出 bill_no 相同的元素并合并
        arr1.forEach((item1) => {
            const billNo1 = item1.u_bill_no;
            const matchingItem2 = arr2.find((item2) => item2.bill_no == billNo1);

            if (matchingItem2) {
                const mergedItem = {};
                // 处理 arr1 元素的键，添加 ori 后缀
                for (const key in item1) {
                    if (item1.hasOwnProperty(key)) {
                        if (key != "phid") {
                            mergedItem[`${key}_ori`] = item1[key];
                        }
                    }
                }
                // 处理 arr2 元素的键，添加 ori 后缀
                for (const key in matchingItem2) {
                    if (matchingItem2.hasOwnProperty(key)) {
                        mergedItem[`${key}`] = matchingItem2[key];
                    }
                }
                // 保留原始的 bill_no 键
                mergedItem.bill_no = billNo1;
                result[2].push(mergedItem);
            }
        });

        return result;
    }
    // 三大费用带出，最新
    function danjvchaxun() {
        //   console.log(`触发了·····`);
        let mxLock = true;
        if (!mstform.getItem("phid_pc")) return;
        dgrid2.clearRows();
        dgrid3.clearRows();
        dgrid4.clearRows();
        // 实施费用变更明细
        if (dgrid2) {
            $NG.execServer("get_impl_cost_budget_info", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                //   console.log(`实施费请求`, res);
                if (res.count == 0) return;
                const data = JSON.parse(res.data);
                //   console.log(res.data);
                //默认增行,批量新增表体数据
                var gridArr = []; //定义表体数组
                let total_amt = 0;
                //请求设备清单的原有数据
                //   console.log(`测试报错`, mstform.getItem("phid_pc").getValue());
                $NG.execServer("getSbqdPayDetailOri", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
                    // console.log(`原实施`, res, mstform.getItem("phid_pc").getValue());
                    let _ori = [];
                    if (res.count !== 0) {
                        _ori = JSON.parse(res.data).reduce((value, item) => {
                            value.push(item.extendObjects);
                            return value;
                        }, []);
                    }
                    // console.log(`原有实施数据`, _ori);
                    let current = data.reduce((value, item) => {
                        value.push(item.extendObjects);
                        return value;
                    }, []);
                    const _arr = compareArrays(_ori, current);
                    // console.log(`合并的二维数组`, _arr);

                    //添加现有数据有原有数据没有的
                    _arr[0].forEach((el1) => {
                        let gridObj = {};
                        gridObj.u_bill_no = el1.bill_no;
                        gridObj.u_total_impl_amt_ori = el1.u_total_impl_amt;
                        gridObj.u_total_impl_labor_amt_ori = el1.u_total_impl_labor_amt;
                        gridObj.u_total_daily_amt_ori = el1.u_total_daily_amt;
                        gridObj.u_total_sec_dev_amt_ori = el1.u_total_sec_dev_amt;
                        gridObj.u_source_phid = el1.u_source_phid;
                        gridArr.push(gridObj);
                    });
                    //添加现有数据没有原有数据有的
                    _arr[1].forEach((el2) => {
                        let gridObj = {};
                        gridObj.u_bill_no = el2.bill_no;
                        gridObj.u_total_impl_amt = el2.u_total_impl_amt;
                        gridObj.u_total_impl_labor_amt = el2.u_total_impl_labor_amt;
                        gridObj.u_total_daily_amt = el2.u_total_daily_amt;
                        gridObj.u_total_sec_dev_amt = el2.u_total_sec_dev_amt;
                        gridObj.u_source_phid = el2.phid;
                        gridArr.push(gridObj);
                    });
                    //添加都有的
                    _arr[2].forEach((el4, index) => {
                        //   console.log(`合并数据`, el4);
                        let gridObj = {};
                        gridObj.u_bill_no = el4.bill_no;
                        gridObj.u_total_impl_amt = el4.u_total_impl_amt;
                        gridObj.u_total_impl_amt_ori = el4.u_total_impl_amt_ori;
                        gridObj.u_total_impl_labor_amt = el4.u_total_impl_labor_amt;
                        gridObj.u_total_impl_labor_amt_ori = el4.u_total_impl_labor_amt_ori;
                        gridObj.u_total_daily_amt = el4.u_total_daily_amt;
                        gridObj.u_total_daily_amt_ori = el4.u_total_daily_amt_ori;
                        gridObj.u_total_sec_dev_amt = el4.u_total_sec_dev_amt;
                        gridObj.u_total_sec_dev_amt_ori = el4.u_total_sec_dev_amt_ori;
                        gridObj.u_source_phid = el4.phid;
                        gridArr.push(gridObj);
                    });
                    // console.log(`实施`, total_amt);
                    while (!mxLock) { }
                    mxLock = false;
                    project_amt.amt = project_amt.amt + total_amt;
                    mxLock = true;
                    //调用新增表体行数据的函数
                    dgrid2.addRows(gridArr);
                });
            });
        }
        if (dgrid3) {
            $NG.execServer(
                "get_svc_cost_budget_info",
                {
                    phid_pc: mstform.getItem("phid_pc").getValue(),
                },
                function (res) {
                    // console.log(`服务请求`, res);
                    if (res.count == 0) return;
                    const data = JSON.parse(res.data);
                    // console.log(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    let total_amt = 0;
                    $NG.execServer("getSbadPayDetailSvcOri", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
                        let _ori = [];
                        if (res.count !== 0) {
                            _ori = JSON.parse(res.data).reduce((value, item) => {
                                value.push(item.extendObjects);
                                return value;
                            }, []);
                        }
                        //   console.log("服务原", _ori);
                        const current = data.reduce((value, item) => {
                            value.push(item.extendObjects);
                            return value;
                        }, []);
                        const _arr = compareArrays(_ori, current);
                        //添加现有数据有原有数据没有的
                        _arr[0].forEach((el1) => {
                            let gridObj = {};
                            gridObj.u_bill_no = el1.bill_no;
                            gridObj.u_total_svc_amt_ori = el1.u_total_svc_amt;
                            gridObj.u_total_svc_labor_amt_ori = el1.u_total_svc_labor_amt;
                            gridObj.u_total_daily_amt_ori = el1.u_total_daily_amt;
                            gridObj.u_source_phid = el1.phid;
                            total_amt = Number(el1.u_total_svc_amt) || 0;
                            gridArr.push(gridObj);
                        });
                        //添加现有数据没有原有数据有的
                        _arr[1].forEach((el2) => {
                            let gridObj = {};
                            gridObj.u_bill_no = el2.u_bill_no;
                            gridObj.u_total_svc_amt = el2.u_total_svc_amt;
                            gridObj.u_total_svc_labor_amt = el2.u_total_svc_labor_amt;
                            gridObj.u_total_daily_amt = el2.u_total_daily_amt;
                            gridObj.u_source_phid = el2.phid;
                            total_amt = Number(el2.u_total_svc_amt) || 0;
                            gridArr.push(gridObj);
                        });
                        //添加都有的
                        _arr[2].forEach((el4, index) => {
                            // console.log(`合并数据`, el4);
                            let gridObj = {};
                            gridObj.u_bill_no = el4.bill_no;
                            gridObj.u_total_svc_amt = el4.u_total_svc_amt;
                            gridObj.u_total_svc_amt_ori = el4.u_total_svc_amt_ori;
                            gridObj.u_total_svc_labor_amt = el4.u_total_svc_labor_amt;
                            gridObj.u_total_svc_labor_amt_ori = el4.u_total_svc_labor_amt_ori;
                            gridObj.u_total_daily_amt = el4.u_total_daily_amt;
                            gridObj.u_total_daily_amt_ori = el4.u_total_daily_amt_ori;
                            gridObj.u_source_phid = el4.phid;
                            total_amt = Number(el4.u_total_svc_amt) || 0;
                            gridArr.push(gridObj);
                        });

                        //   console.log(`服务`, total_amt);
                        while (!mxLock) { }
                        mxLock = false;
                        project_amt.amt = project_amt.amt + total_amt;
                        mxLock = true;
                        //调用新增表体行数据的函数
                        dgrid3.addRows(gridArr);
                    });
                }
            );
        }
        if (dgrid4) {
            $NG.execServer("getDevCostBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                // console.log(`研发费请求`, res);
                if (res.count == 0) return;
                const data = JSON.parse(res.data);
                //   console.log(res.data);
                //默认增行,批量新增表体数据
                var gridArr = []; //定义表体数组
                var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                $NG.execServer("getSbqdPayDetailSelfOri", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
                    // console.log("原二开费用", res);
                    let _ori = [];
                    if (res.count !== 0) {
                        _ori = JSON.parse(res.data).reduce((value, item) => {
                            value.push(item.extendObjects);
                            return value;
                        }, []);
                    }
                    let current = data.reduce((value, item) => {
                        value.push(item.extendObjects);
                        return value;
                    }, []);
                    const _arr = compareArrays(_ori, current);
                    //添加现有数据有原有数据没有的
                    _arr[0].forEach((el1) => {
                        let gridObj = {};
                        gridObj.u_bill_no = el1.bill_no;
                        gridObj.u_rdrg_expenses_total_ori = el1.u_total_labor_amt;
                        gridObj.u_rcfy_total_ori = el1.u_total_daily_amt;
                        gridObj.u_rd_expenses_ori = el1.u_rd_expenses;
                        gridObj.u_source_phid = el1.phid;
                        total_amt = Number(el1.u_total_dev_amt) || 0;
                        gridArr.push(gridObj);
                    });
                    //添加现有数据没有原有数据有的
                    _arr[1].forEach((el2) => {
                        let gridObj = {};
                        gridObj.u_bill_no = el2.bill_no;
                        gridObj.u_rdrg_expenses_total = el2.u_total_labor_amt;
                        gridObj.u_rcfy_total = el2.u_total_daily_amt;
                        gridObj.u_rd_expenses = el2.u_total_dev_amt;
                        gridObj.u_source_phid = el2.phid;
                        total_amt = Number(el2.u_total_dev_amt) || 0;
                        gridArr.push(gridObj);
                    });
                    //添加都有的
                    _arr[2].forEach((el4, index) => {
                        //   console.log(`合并数据`, el4);
                        let gridObj = {};
                        gridObj.u_bill_no = el4.bill_no;
                        gridObj.u_rdrg_expenses_total = el4.u_total_labor_amt;
                        gridObj.u_rdrg_expenses_total_ori = el4.u_rdrg_expenses_total_ori;
                        gridObj.u_rcfy_total = el4.u_total_daily_amt;
                        gridObj.u_rcfy_total_ori = el4.u_rcfy_total_ori;
                        gridObj.u_rd_expenses = el4.u_total_dev_amt;
                        gridObj.u_rd_expenses_ori = el4.u_rd_expenses_ori;
                        gridObj.u_source_phid = el4.phid;
                        total_amt = Number(el4.u_total_dev_amt) || 0;
                        gridArr.push(gridObj);
                    });
                    // console.log(`yanfa `, total_amt);
                    while (!mxLock) { }
                    mxLock = false;
                    project_amt.amt = project_amt.amt + total_amt;
                    mxLock = true;
                    //调用新增表体行数据的函数
                    dgrid4.addRows(gridArr);
                });
            });
        }
    }

    let qzLock = true;
    //获取签证明细（合同明细）
    function getQzInfo() {
        if (!qzLock) return;
        qzLock = false;
        setTimeout(() => {
            const gridArr = [];
            // console.log(`签证单子`, dgrid5);
            if (dgrid5) {
                //   console.log(`合同gi`, mstform.getItem("u_cnt_id").getValue());
                $NG.execServer("getCntDetail", { phid: mstform.getItem("u_cnt_id").getValue() }, (res) => {
                    console.log(`签证请求`, res);
                    if (res.count == 0) return;
                    const _data = JSON.parse(res.data).reduce((value, item) => {
                        value.push(item.extendObjects);
                        return value;
                    }, []);
                    let _temp = JSON.parse(res.data);
                    _temp = _temp.sort((a, b) => (Number(a.extendObjects.item_no) || 0) - (Number(b.extendObjects.item_no) || 0));
                    window.cnt_no_max = Number(_temp[_temp.length - 1].extendObjects.item_no);
                    console.log(`签证明细`, _data);
                    _data.forEach((el5) => {
                        const gridObj = {};
                        gridObj.u_cnt_no = el5.item_no;
                        gridObj.u_cnt_list_name = el5.item_name;
                        gridObj.u_unit = el5.phid_unit;
                        gridObj.u_unit_EXName = el5.msname;
                        gridObj.u_tech_params = el5.user_jscs;
                        gridObj.u_pc_subitem_category = el5.user_gcfxfl;
                        gridObj.u_secp = el5.user_ggxh;
                        gridObj.u_qty_ori = el5.qty;
                        gridObj.u_qty = el5.qty;
                        gridObj.u_rate = el5.taxrate;
                        gridObj.u_prc_ori = el5.prc_fc;
                        gridObj.u_cnt_prc = el5.prc_fc;
                        gridObj.u_prc_vat_ori = el5.prc_vat_fc;
                        gridObj.u_cnt_prc_vat = el5.prc_vat_fc;
                        gridObj.u_amt_vat_ori = el5.amt_vat_fc;
                        gridObj.u_cnt_amt_vat = el5.amt_vat_fc;
                        gridObj.u_cnt_amt_vat_ori = el5.amt_vat_fc;
                        gridObj.u_amt_ori = el5.amt_fc;
                        gridObj.u_cnt_amt = el5.amt_fc;
                        gridObj.u_cnt_amt_ori = el5.amt_fc;
                        gridObj.u_source_phid = el5.cntd_phid;
                        gridArr.push(gridObj);
                    });
                    if (page.oType == "view") return;
                    console.log("执行签证插入", dgrid5);
                    dgrid5.addRows(gridArr);
                    // dgrid5.clearRows().then(() => {
                    //   dgrid5.addRows(gridArr);
                    //   qzLock = true
                    // });
                });
            }
        }, 300);
    }
    //获取合同数量
    function getCntCount(table, key, fun) {
        if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
        $NG.execServer(
            "getCntCount",
            {
                type: 1,
                phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue(),
            },
            (res) => {
                //   console.log(res, "count");
                switch (res.count) {
                    case 0:
                        return;
                    case 1:
                        const datas = JSON.parse(res.data)[0].extendObjects;
                        const temp_map = {};
                        temp_map[key] = datas.phid;
                        temp_map[`${key}_EXName`] = datas.bill_name;
                        $NG.updateState((updater) => {
                            updater.data[table].setProps({
                                ...temp_map,
                            });
                            setTimeout(() => {
                                if (fun) {
                                    fun();
                                }
                            }, 200);
                        });
                }
            }
        );
    }
    let lock = false;
    // 签证变更引用检查设备清单明细是否包含成本信息
    function getSbqdInfoByCntItem(element, sourceid) {
        try {
            lock = true;
            const map = { ...element };
            console.log(`查询中`, sourceid, element);
            if (sourceid) {
                $NG.execServer("getSbqdDetailByCntItem", { phid: sourceid }, (res) => {
                    while (lock) {
                        console.log(`锁`);
                    }
                    if (res.count !== 0) {
                        const data = JSON.parse(res.data).reduce((value, item) => {
                            value.push(item.extendObjects);
                            return value;
                        }, []);
                        const el = { ...map };
                        data.forEach((item) => {
                            el.u_sub_item_ori = item.u_sub_item;
                            el.u_revenue_type = item.u_revenue_type;
                            el.u_revenue_type_EXName = item.ur_exname;
                            el.u_sub_item = item.u_sub_item;
                            el.u_sub_name_ori = item.u_sub_name;
                            el.u_sub_name = item.u_sub_name;
                            el.u_sub_item_msunit_ori = item.u_sub_item_msunit;
                            el.u_sub_item_msunit_ori_EXName = item.u_sub_item_msunit_exname;
                            el.u_sub_item_msunit = item.u_sub_item_msunit;
                            el.u_sub_item_msunit_EXName = item.u_sub_item_msunit_exname;
                            el.u_sub_spec_ori = item.u_sub_ggxh;
                            el.u_sub_spec = item.u_sub_ggxh;
                            el.u_sub_item_category_ori = item.u_sub_item_category;
                            el.u_sub_item_category_ori_EXName = item.u_sub_item_category_exname;
                            el.u_sub_item_category = item.u_sub_item_category;
                            el.u_sub_item_category_EXName = item.u_sub_item_category_exname;
                            el.u_sub_guide_prc = item.u_fwgczdj;
                            el.u_sub_qty_ori = item.u_sub_qty;
                            el.u_sub_qty = item.u_sub_qty;
                            el.u_sub_tax_rate_ori = item.u_sub_tax_rate;
                            el.u_sub_tax_rate = item.u_sub_tax_rate;
                            el.u_sub_prc_ori = item.u_sub_prc;
                            el.u_sub_prc = item.u_sub_prc;
                            el.u_sub_prc_vat_ori = item.u_sub_prc_vat;
                            el.u_sub_prc_vat = item.u_sub_prc_vat;
                            el.u_sub_cost_ori = item.u_sub_cost;
                            el.u_sub_cost = item.u_sub_cost;
                            el.u_sub_cost_vat_ori = item.u_sub_cost_vat;
                            el.u_sub_cost_vat = item.u_sub_cost_vat;

                            el.u_pur_item_ori = item.u_pur_item;
                            el.u_pur_item = item.u_pur_item;
                            el.u_pur_name_ori = item.u_pur_name;
                            el.u_pur_name = item.u_pur_name;
                            el.u_pur_item_msunit_ori = item.u_pur_item_msunit;
                            el.u_pur_item_msunit_ori_EXName = item.u_pur_item_msunit_exname;
                            el.u_pur_item_msunit = item.u_pur_item_msunit;
                            el.u_pur_item_msunit_EXName = item.u_pur_item_msunit_exname;
                            el.u_pur_spec_ori = item.u_pur_ggxh;
                            el.u_pur_spec = item.u_pur_ggxh;
                            el.u_pur_item_category_ori = item.u_pur_item_category;
                            el.u_pur_item_category_ori_EXName = item.u_pur_item_category_exname;
                            el.u_pur_item_category = item.u_pur_item_category;
                            el.u_pur_item_category_EXName = item.u_pur_item_category_exname;
                            el.u_pur_guide_prc = item.u_cgzdj;
                            el.u_pur_qty_ori = item.u_pur_qty;
                            el.u_pur_qty = item.u_pur_qty;
                            el.u_rest_qty = item.u_rest_qty;
                            el.u_pur_tax_rate_ori = item.u_pur_tax_rate;
                            el.u_pur_tax_rate = item.u_pur_tax_rate;
                            el.u_pur_prc_ori = item.u_pur_prc;
                            el.u_pur_prc = item.u_pur_prc;
                            el.u_pur_prc_vat_ori = item.u_pur_prc_vat;
                            el.u_pur_prc_vat = item.u_pur_prc_vat;
                            el.u_pur_cost_ori = item.u_pur_cost;
                            el.u_pur_cost = item.u_pur_cost;
                            el.u_pur_cost_vat_ori = item.u_pur_cost_vat;
                            el.u_pur_cost_vat = item.u_pur_cost_vat;

                            el.u_self_item_ori = item.u_self_item;
                            el.u_self_item = item.u_self_item;
                            el.u_self_name_ori = item.u_self_name;
                            el.u_self_name = item.u_self_name;
                            el.u_self_item_msunit_ori = item.u_self_item_msunit;
                            el.u_self_item_msunit_ori_EXName = item.u_self_item_msunit_exname;
                            el.u_self_item_msunit = item.u_self_item_msunit;
                            el.u_self_item_msunit_EXName = item.u_self_item_msunit_exname;
                            el.u_self_spec_ori = item.u_self_ggxh;
                            el.u_self_spec = item.u_self_ggxh;
                            el.u_self_item_category_ori = item.u_self_item_category;
                            el.u_self_item_category_ori_EXName = item.u_self_item_category_exname;
                            el.u_self_item_category = item.u_self_item_category;
                            el.u_self_item_category_EXName = item.u_self_item_category_exname;
                            el.u_zzzdj = item.u_zzzdj;
                            el.u_self_qty_ori = item.u_self_qty;
                            el.u_self_qty = item.u_self_qty;
                            el.u_nzz_rest_qty = item.u_nzz_rest_qty;
                            el.u_self_tax_rate_ori = item.u_self_tax_rate;
                            el.u_self_tax_rate = item.u_self_tax_rate;
                            el.u_self_prc_ori = item.u_self_prc;
                            el.u_self_prc = item.u_self_prc;
                            el.u_self_prc_vat_ori = item.u_self_prc_vat;
                            el.u_self_prc_vat = item.u_self_prc_vat;
                            el.u_self_cost_ori = item.u_self_cost;
                            el.u_self_cost = item.u_self_cost;
                            el.u_self_cost_vat_ori = item.u_self_cost_vat;
                            el.u_self_cost_vat = item.u_self_cost_vat;
                            el.u_source_phid = item.phid;
                            console.log(`新增+1`, 1);
                            dgrid1.addRows([{ ...el }]);
                        });
                        lock = false;
                    } else {
                        console.log(`新增+1`, 2);
                        dgrid1.addRows([{ ...element }]);
                        lock = false;
                    }
                });
            } else {
                console.log(`新增+1`, 3);
                dgrid1.addRows([{ ...element }]);
                lock = false;
            }
            lock = false;
        } catch (err) {
            lock = false;
            console.error(err);
        }
    }

    // 签证明细 -- 设备清单明细
    function qzInfoToSbqdInfo() {
        let row5 = dgrid5.getRows();
        const row1 = dgrid1.getRows();
        if (row5.length !== 0) {
            // mstform.setReadOnly("u_alter_type", true);
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_equipment_chg.u_alter_type.setProps({
                    // hidden: true, //隐藏
                    // required: true, //必输
                    disabled: true, //只读
                });
            });
        } else {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_equipment_chg.u_alter_type.setProps({
                    // hidden: true, //隐藏
                    // required: true, //必输
                    disabled: false, //只读
                });
            });
            // mstform.setReadOnly("u_alter_type", false);
        }
        // 设置唯一标识
        row5.forEach((item) => {
            // if (!item.u_source_phid) {
            if (!item.u_bridge_key) {
                const str = generate15DigitNumber();
                item.u_bridge_key = str;
                item.u_phid = str;
                // 设备清单明细新增行
                const row_temp = {
                    u_cnt_item_no: item.u_cnt_no,
                    u_cnt_item_EXName: item.u_cnt_list_name,
                    u_cnt_item_name: item.u_cnt_list_name,
                    u_cnt_item: item.u_source_phid || item.u_phid,
                    u_eq_item_no: item.u_cnt_no,
                    u_eq_item_name: item.u_cnt_list_name,
                    u_change_type: "2",
                    u_status: "1",
                    u_msunit: item.u_unit, //单位
                    u_spec: item.u_secp, //规格
                    u_pc_subitem_category: item.u_pc_subitem_category, //分项
                    u_brand_name: item.u_brand_name, //品牌
                    u_tech_params: item.u_tech_params, //技术参数
                    u_qty: item.u_qty, //数量
                    u_cnt_prc: item.u_cnt_prc, //合同未税单价
                    u_cnt_amt_vat: item.u_cnt_amt_vat, //含税单价
                    u_cnt_amt_vat_ori: item.u_cnt_amt_vat, //含税单价
                    u_cnt_amt: item.u_cnt_amt, //合同未税金额
                    u_cnt_amt_ori: item.u_cnt_amt, //合同未税金额
                    u_bridge_key: item.u_bridge_key,
                };
                setTimeout(() => {
                    getSbqdInfoByCntItem(row_temp, item.u_source_phid);
                });
                // row5 = dgrid5.getRows();
            } else {
                // 匹配唯一标识，更改数据
                row1.forEach((elem) => {
                    if (elem.u_bridge_key && elem.u_bridge_key == item.u_bridge_key) {
                        // console.log(`发生1次`);
                        elem.u_cnt_item_no = item.u_cnt_no;
                        elem.u_cnt_item_EXName = item.u_cnt_list_name;
                        elem.u_cnt_item = item.u_phid;
                        (elem.u_cnt_item_name = item.u_cnt_list_name), (elem.u_cnt_item = item.u_source_phid || item.u_phid), (elem.u_eq_item_no = item.u_cnt_no);
                        elem.u_eq_item_name = item.u_cnt_list_name;
                        elem.u_msunit = item.u_unit; //单位
                        elem.u_msunit_EXName = item.u_unit_EXName; //单位
                        elem.u_spec = item.u_secp; //规格
                        elem.u_pc_subitem_category = item.u_pc_subitem_category; //分项
                        elem.u_brand_name = item.u_brand_name; //品牌
                        elem.u_tech_params = item.u_tech_params; //技术参数
                        elem.u_qty = item.u_qty; //数量
                        elem.u_cnt_item_tax_rate = item.u_rate; // 税率
                        elem.u_cnt_prc_vat = item.u_cnt_prc_vat; // 合同含税单价
                        elem.u_cnt_prc = item.u_cnt_prc; //合同未税单价
                        elem.u_cnt_amt_vat = item.u_cnt_amt_vat; //含税金额
                        // elem.u_cnt_amt_vat_ori = item.u_cnt_amt_vat; //含税金额
                        elem.u_cnt_amt = item.u_cnt_amt; //合同未税金额
                        // elem.u_cnt_amt_ori = item.u_cnt_amt; //合同未税金额
                    }
                });
            }
            // }
        });
        // 同时删除逻辑
        row1.forEach((i) => {
            let lock = false;
            if (i.u_bridge_key) {
                row5.forEach((j) => {
                    if (i.u_bridge_key && i.u_bridge_key == j.u_bridge_key) {
                        lock = true;
                    }
                });
                if (!lock) {
                    dgrid1.deleteRow(i);
                }
            }
        });
        dgrid1.refreshView();
    }

    //匹配物料专用
    function matchingWl(args) {
        const _arr = dgrid1.getRows();
        if (args) {
            fun(args);
        } else {
            _arr.forEach((items) => {
                fun(items);
            });
        }
        //内置函数（多功能控制）
        function fun(items) {
            // console.log(items, items.u_sub_item, items.u_sub_name?.trim(), String(items.u_sub_item_category || "").trim(), String(items.u_sub_item_msunit || "").trim(), items.u_sub_spec?.trim());
            if (items.u_sub_item) {
                $NG.execServer("getItemdataByPhid", { phid: items.u_sub_item }, function (res) {
                    window.sNum += 1;
                    if (res.count > 0) {
                        var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        //   console.log(`匹配信息`, data);
                        items.u_sub_item_category = data.phid_resbs;
                        items.u_sub_item_category_EXName = data.name;
                        items.u_sub_name = data.itemname;
                        items.u_sub_spec = data.spec;
                        items.u_sub_item_msunit_EXName = data.msunit_name;
                        items.u_sub_item_msunit = data.msunit_phid;
                        items.u_sub_item_category = data.phid_resbs;
                        items.u_sub_item_category_EXName = data.res_bs_name;
                        items.u_fwgczdj = data.prc_ad;
                    }
                    dgrid1.refreshView();
                });
            } else if (!items.u_sub_item && items.u_sub_name?.trim() && String(items.u_sub_item_category || "").trim() && String(items.u_sub_item_msunit || "").trim() && items.u_sub_spec?.trim()) {
                $NG.execServer("getItemDataByName", { itemname: `'${items.u_sub_name}'`, spec: `'${items.u_sub_spec}'`, msunit: items.u_sub_item_msunit }, function (res) {
                    window.sNum += 1;
                    if (res && res.count > 0) {
                        //   console.log("execServer:getItemDataByName");
                        let data = JSON.parse(res.data)[0].extendObjects; // 单返回值
                        items.u_sub_item = data.phid;
                        items.u_sub_item_EXName = data.itemno;
                        dgrid1.refreshView();
                        //   console.log("接口");
                    } else {
                        window._list.push({
                            user_is_bz: items.user_is_bz,
                            ItemName: items.u_sub_name,
                            PhidResbs: items.u_sub_item_category,
                            PhidMsunit: items.u_sub_item_msunit,
                            Spec: items.u_sub_spec,
                            ResBsCode: items.u_sub_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                            ResourceType: "8570000000000002", // 假设资源类型是固定的
                        });
                    }
                });
            }
            //2. 更新拟采购项
            if (items.u_pur_item) {
                $NG.execServer("getItemdataByPhid", { phid: items.u_pur_item }, function (res) {
                    window.newNum += 1;
                    if (res.count > 0) {
                        var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值

                        items.u_pur_item_category = purdata.phid_resbs;
                        items.u_pur_item_category_EXName = purdata.name;
                        items.u_pur_name = purdata.itemname;
                        items.u_pur_spec = purdata.spec;
                        items.u_pur_item_msunit_EXName = purdata.msunit_name;
                        items.u_pur_item_msunit = purdata.msunit_phid;
                        items.u_pur_item_category = purdata.phid_resbs;
                        items.u_pur_item_category_EXName = purdata.res_bs_name;
                        items.u_pur_guide_prc = purdata.prc_ad;
                    } else {
                    }
                    dgrid1.refreshView();
                });
                $NG.execServer("getIsDj", { phid_wl: items.u_pur_item, phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
                    window.sNum += 1;
                    if (res.count == 0) return;
                    const _data = JSON.parse(res.data)[0].extendObjects;
                    items.u_priced_prc = _data.u_target_prc;
                    items.u_is_priced = 1;
                    dgrid1.refreshView();
                });
            } else if (!items.u_pur_item && items.u_pur_name?.trim() && String(items.u_pur_item_category || "").trim() && String(items.u_pur_item_msunit || "").trim() && items.u_pur_spec?.trim()) {
                $NG.execServer("getItemDataByName", { itemname: "'" + items.u_pur_name + "'", spec: "'" + items.u_pur_spec + "'", msunit: items.u_pur_item_msunit }, function (res) {
                    window.sNum += 1;
                    if (res.count > 0) {
                        let data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_pur_item = data.phid;
                        items.u_pur_item_EXName = data.itemno;
                        //   console.log("接口");
                        dgrid1.refreshView();
                    } else {
                        window._list.push({
                            user_is_bz: items.user_is_bz,
                            ItemName: items.u_pur_name,
                            PhidResbs: items.u_pur_item_category,
                            PhidMsunit: items.u_pur_item_msunit,
                            Spec: items.u_pur_spec,
                            ResBsCode: items.u_pur_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                            ResourceType: "2", // 假设资源类型是固定的
                        });
                    }
                });
            }

            //3. 更新拟自制项
            if (items.u_self_item) {
                $NG.execServer("getItemdataByPhid", { phid: items.u_self_item }, function (res) {
                    window.sNum += 1;
                    if (res.count > 0) {
                        var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_self_item_category = data.phid_resbs;
                        items.u_self_item_category_EXName = data.name;
                        items.u_self_name = data.itemname;
                        items.u_self_spec = data.spec;
                        items.u_self_item_msunit = data.msunit_phid;
                        items.u_self_item_msunit_EXName = data.msunit_name;
                        items.u_self_item_category_EXName = data.res_bs_name;
                        items.u_self_item_category = data.phid_resbs;
                        items.u_zzzdj = data.prc_ad;
                    }
                    dgrid1.refreshView();
                });
            } else if (!items.u_self_item && items.u_self_name?.trim() && String(items.u_self_item_category).trim() && String(items.u_self_item_msunit).trim() && items.u_self_spec?.trim()) {
                $NG.execServer("getItemDataByName", { itemname: "'" + items.u_self_name + "'", spec: "'" + items.u_self_spec + "'", msunit: items.u_self_item_msunit }, function (res) {
                    window.sNum += 1;
                    if (res.count > 0) {
                        let data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        items.u_self_item = data.phid;
                        items.u_self_item_EXName = data.itemno;
                        dgrid1.refreshView();
                        //   console.log("接口");
                    } else {
                        window._list.push({
                            user_is_bz: items.user_is_bz,
                            ItemName: items.u_self_name,
                            PhidResbs: items.u_self_item_category,
                            PhidMsunit: items.u_self_item_msunit,
                            Spec: items.u_self_spec,
                            ResBsCode: items.u_self_item_category, // 假设 ResBsCode 是固定值，需根据实际情况调整
                            ResourceType: "8570000000000001", // 假设资源类型是固定的
                        });
                    }
                    dgrid1.refreshView()

                });
            }
        }
    }

    // 获取累计清单成本
    getSbqdTotalGapAmt();
    function getSbqdTotalGapAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue();
        if (!phid_pc) return;
        $NG.execServer("getSbqdTotalGapAmt", { phid_pc }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            window._catch_eq_totalAmt = _data;
        });
    }
});
